package com.todo.strategy.offline.application.handler.statusChange;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.todo.common.common.entity.response.BizResponse;
import com.todo.common.utils.TodoCommonUtils;
import com.todo.component.redis.RedisService;
import com.todo.strategy.common.constant.StrategyOfflineKeyBuild;
import com.todo.strategy.common.constant.StrategyOnlineKeyBuild;
import com.todo.strategy.common.enums.StrategyStatusEnum;
import com.todo.strategy.offline.application.entity.bo.PlatformStrategyBO;
import com.todo.strategy.offline.application.entity.context.StrategyStatusContext;
import com.todo.strategy.offline.application.remote.StrategyPipelineRemoteService;
import com.todo.strategy.offline.application.service.PlatformStrategyService;
import com.todo.strategy.offline.infrastructure.repository.PlatformStrategyRepository;
import com.todo.strategy.pipeline.common.enums.OperateActionEnum;
import com.todo.strategy.pipeline.common.enums.StrategyActionEnum;
import com.todo.strategy.pipeline.service.api.request.OfflineToOnlineRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author azhebuxing
 * @date 2024/12/12 19:37
 * @description
 */
@Slf4j
@Component
public class PublishedHandler extends AbstractStrategyStatusHandler {

    @Resource
    private PlatformStrategyService platformStrategyService;
    @Resource
    private PlatformStrategyRepository platformStrategyRepository;
    @Resource
    private RedisService redisService;
    @Resource
    private StrategyPipelineRemoteService strategyPipelineRemoteService;


    @Override
    protected Boolean doStatusHandle(StrategyStatusContext context) {
        Long strategyId = context.getStrategyId();
        PlatformStrategyBO strategyInfoBO = platformStrategyService.queryPlatformStrategyInfoById(strategyId);
        if (strategyInfoBO == null) {
            log.error("PublishedHandler#doStatusHandle 平台攻略发布状态处理完成，数据为空，默认执行成功 context:{}", JSONObject.toJSONString(context));
            return true;
        }
        if (!strategyInfoBO.getStatus().equals(context.getCurrentStatus())) {
            log.error("PublishedHandler#doStatusHandle 平台攻略当前数据状态与发送消息状态不一致，无法处理当前状态下的数据情况 context:{}，当前状态 :{}", JSONObject.toJSONString(context), strategyInfoBO.getStatus());
            return true;
        }
        String detailKey = StrategyOnlineKeyBuild.strategyUserInfoKey(strategyId);
        redisService.set8H(detailKey, JSONObject.toJSONString(strategyInfoBO));

        String insertTagKey = StrategyOfflineKeyBuild.pStrategyInsertTagKey(strategyId);
        Boolean inserted = redisService.hasKey(insertTagKey);
        redisService.del(insertTagKey);
        //insert
        if (inserted) {
            OfflineToOnlineRequest insertRequest = new OfflineToOnlineRequest();
            insertRequest.setBusinessId(strategyId);
            //唯一标识 攻略id+更新时间hash 注：后续如果新增版本概念可以通过id+version确认
            insertRequest.setUniKey(TodoCommonUtils.buildStriHashKey(strategyId, strategyInfoBO.getUpdateTime()));
            insertRequest.setStrategyActionEnum(StrategyActionEnum.PLATFORM_STRATEGY);
            insertRequest.setOperateActionEnum(OperateActionEnum.INSERT);
            insertRequest.setOriginData(JSON.toJSONString(platformStrategyRepository.queryPlatformStrategyById(strategyId)));
            BizResponse<Boolean> bizResponse = strategyPipelineRemoteService.offlineToOnlineAsync(insertRequest);
            if (bizResponse == null || !bizResponse.isSuccess() || !bizResponse.getData()) {
                log.error("PublishedHandler#doStatusHandle 平台攻略发布状态处理失败，数据同步失败 context:{}", JSONObject.toJSONString(context));
            }
            return true;
        }
        //update
        OfflineToOnlineRequest updateRequest = new OfflineToOnlineRequest();
        updateRequest.setBusinessId(strategyId);
        //唯一标识 攻略id+更新时间hash 注：后续如果新增版本概念可以通过id+version确认
        updateRequest.setUniKey(TodoCommonUtils.buildStriHashKey(strategyId, strategyInfoBO.getUpdateTime()));
        updateRequest.setStrategyActionEnum(StrategyActionEnum.PLATFORM_STRATEGY);
        updateRequest.setOperateActionEnum(OperateActionEnum.UPDATE);
        updateRequest.setOriginData(JSON.toJSONString(platformStrategyRepository.queryPlatformStrategyById(strategyId)));
        BizResponse<Boolean> updateResponse = strategyPipelineRemoteService.offlineToOnlineAsync(updateRequest);
        if (updateResponse == null || !updateResponse.isSuccess() || !updateResponse.getData()) {
            log.error("PublishedHandler#doStatusHandle 平台攻略发布状态处理失败，数据同步失败 context:{}", JSONObject.toJSONString(context));
        }

        return true;
    }

    @Override
    protected boolean match(StrategyStatusContext context) {
        if (context == null || context.getStrategyId() == null || context.getCurrentStatus() == null) {
            log.error("PublishedHandler#match 平台攻略前置数据匹配失败，数据缺失或不存在 context:{}", JSONObject.toJSONString(context));
            return false;
        }
        return true;
    }

    @Override
    protected StrategyStatusEnum doGetDealStatus() {
        return StrategyStatusEnum.PUBLISHED;
    }
}
